package cc.wanforme.chipmunity.security.handlers;

import com.alibaba.fastjson.JSON;

import cc.wanforme.chipmunity.common.CookieUtil;
import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.security.service.PersistentLoginService;

import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 退出成功处理器
 */
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

	private final PersistentLoginService persistentLoginService;
	public CustomLogoutSuccessHandler(PersistentLoginService persistentLoginService) {
		this.persistentLoginService = persistentLoginService;
	}
	
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = CookieUtil.getCookieValue(request, CustomTokenFilter.TOKEN_NAME);
    	persistentLoginService.removePersistentLogin(token);
    	response.addCookie(new Cookie(CustomTokenFilter.TOKEN_NAME, null));
    	
    	WebResponse httpServletResponse = WebResponse.success("退出成功");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.getWriter().write(JSON.toJSONString(httpServletResponse));
    }

}
